package cn.hicard.auth.web.tag;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import cn.hicard.auth.web.AuthFilter;
import cn.hicard.auth.web.Node;
import cn.hicard.util.AppConfig;

/**
 * 侧边栏菜单标签，无权限项不显示
 * @author zhangyu
 *
 */
public class MenuTag extends BodyTagSupport {
	
	private static final long serialVersionUID = -2569903008649636846L;
	
	private String authId = null;
	
	public void setAuthId(String authId) {
		this.authId = authId;
	}

	@Override
	public int doEndTag() throws JspException {
		// 从会话缓存中取得总菜单节点// || menuNode.getChildren() == null || menuNode.getChildren().size() == 0
		Node allMenuNode = (Node)((HttpServletRequest)pageContext.getRequest()).getSession().getAttribute(AuthFilter.USER_MENU_TREE);
		if(allMenuNode == null || authId == null){
			return super.doEndTag();
		}
		// 找出当前系统总菜单节点
		Node menuNode = allMenuNode.findChild(AppConfig.get("system.source_id"));
		if(menuNode == null){
			return super.doEndTag();
		}
		// 代表当前标签的资源节点
		Node node = null;
		MenuTag parent = (MenuTag)getParent();		
		// 如果父标签为空，则本身是一级菜单
		if(parent == null){
			node = menuNode.findChild(authId);
		}
		// 如果有父标签，则本身是二级菜单
		else{
			Node parentNode = menuNode.findChild(parent.authId);
			if(parentNode == null){
				return super.doEndTag();
			}else{
				node = parentNode.findChild(authId);
			}
		}
		// 找到了当前菜单点节则代表有权限
		if(node != null){
			try {
				pageContext.getOut().println(getBodyContent().getString());
			} catch (IOException e) {
				throw new JspException("IOError while writing the body: " + e.getMessage(), e);
			}
		}
		return super.doEndTag();
	}

}
